package com.wyg.blog.controller.manage_blog;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyg.blog.model.user.FriendSite;
import com.wyg.blog.service.user.FriendSiteService;
import com.wyg.blog.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: WYG
 * @time: 2021/1/31 9:05
 */
@RestController
@RequestMapping("/api/friend")
public class FriendSiteController {

    @Autowired
    FriendSiteService friendSiteService;

    @GetMapping("/getSites")
    @CrossOrigin
    @PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
    public JsonResult<IPage<FriendSite>> getSites(@RequestParam("current") Integer current, @RequestParam("size") Integer size) {
        Page<FriendSite> page = new Page<>(current, size);
        IPage<FriendSite> friendSites = friendSiteService.selectAllSite(page);
        return new JsonResult<>(friendSites, "200", "获取友链信息成功");
    }

    @PostMapping("/addSite")
    @CrossOrigin
    @PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
    public JsonResult<Boolean> addSite(@RequestBody FriendSite friendSite) {
        boolean res = friendSiteService.insertSite(friendSite);
        if (res) {
            return new JsonResult<>(true, "200", "添加成功");
        } else {
            return new JsonResult<>(false, "1101", "添加失败");
        }
    }

    @PostMapping("/deleteSite")
    @CrossOrigin
    @PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
    public JsonResult<Boolean> deleteSite(@RequestBody Integer id) {
        boolean res = friendSiteService.removeSite(id);
        if (res) {
            return new JsonResult<>(true, "200", "删除成功");
        } else {
            return new JsonResult<>(false, "1102", "删除失败");
        }
    }

    @GetMapping("/updateStatus")
    @CrossOrigin
    @PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
    public JsonResult<Boolean> updateStatus(@RequestParam("sid") Integer sid) {
        boolean isAdded = friendSiteService.selectStatus(sid);
        boolean res = friendSiteService.renewSiteStatus(sid, !isAdded);
        if (res) {
            return new JsonResult<>(true, "200", "状态修改成功");
        } else {
            return new JsonResult<>(false, "1103", "状态修改失败");
        }
    }

    @PostMapping("/updateSite")
    @CrossOrigin
    @PreAuthorize("hasAnyRole('ADMIN','SUPER_ADMIN')")
    public JsonResult<Boolean> updateSite(@RequestBody FriendSite friendSite) {
        boolean res = friendSiteService.renewSite(friendSite);
        if (res) {
            return new JsonResult<>(true, "200", "修改成功");
        } else {
            return new JsonResult<>(false, "1104", "修改失败");
        }
    }

}
